package com.cskaoyan.controller.admin;
import com.cskaoyan.bean.bo.UpdatePasswordBO;
import com.cskaoyan.bean.entity.Admin;
import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.bean.vo.DataBean;
import com.cskaoyan.bean.vo.DataDTO;
import com.cskaoyan.bean.vo.InfoBean;
import com.cskaoyan.common.aop.OperateLog;
import com.cskaoyan.service.AuthServicelmpl;
import com.cskaoyan.shiro.MallToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
public class AuthController {
    @Autowired
    AuthServicelmpl authServicelmpl;

    /**
     * 没有引入Shiro之前的方法（抛弃）
     * @param token
     * @return
     */
    /*@RequestMapping("admin/auth/login")
    public BaseRespVo login(@RequestBody Map map) {
        String username = (String)map.get("username");
        String password = (String)map.get("password");
        //执行登录业务，并且响应结果
        //登录业务先略，Shiro框架之后写这部分业务
        DataBean dataBean = new DataBean();
        DataBean.AdminInfoBean adminInfo = new DataBean.AdminInfoBean();
        adminInfo.setAvatar("https://dss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/logo_white-d0c9fe2af5.png");
        adminInfo.setNickName("admin123");
        dataBean.setAdminInfo(adminInfo);
        //token是sessionId
        dataBean.setToken("587e315d-0ac3-47a0-9857-7e625ce866ee");
        return BaseRespVo.ok(dataBean);
    }*/


    /**
     * shiro认证
     * @param map
     * @return
     */
    @OperateLog(opType = "安全操作",opAction = "登录")
    @RequestMapping("admin/auth/login")
//    @RequestMapping({"admin/auth/login","wx/auth/login"})
    public BaseRespVo login(@RequestBody Map map) {
        String username = (String)map.get("username");
        String password = (String)map.get("password");
        Subject subject = SecurityUtils.getSubject();
        MallToken authenticationToken = new MallToken(username, password,"market");
        subject.login(authenticationToken);    //subject.login：执行登录   subject.logout：执行登出
        //详细逻辑：subject.login → 认证 → Authenticator执行认证（相当于一个令牌，通常指的是：用户名和密码）
        boolean authenticated = subject.isAuthenticated();   //true:放行
        Object primaryPrincipal = subject.getPrincipals().getPrimaryPrincipal();    //获得用户信息principal
        Admin principal = (Admin) primaryPrincipal;    //强制转化

        DataBean dataBean = new DataBean();
        DataBean.AdminInfoBean adminInfo = new DataBean.AdminInfoBean();
        adminInfo.setAvatar(principal.getAvatar());
        adminInfo.setNickName(principal.getUsername());
        dataBean.setAdminInfo(adminInfo);
        dataBean.setToken((String) subject.getSession().getId());
        System.out.println("login请求的sessionId：" + subject.getSession().getId());

        return BaseRespVo.ok(dataBean);
    }


    /**
     * 引入Shiro之后的方法（推荐）
     * @param token
     * @return
     */
    //可以做窄化请求
    @RequestMapping("admin/auth/info")
    public BaseRespVo info(String token) {
        //1.通过SecurityUtils获取subject主体，进而获得对应的sessionId（在登录处，存储在session对应的session中）
        Subject subject = SecurityUtils.getSubject();   //使用SecurityUtils默认的工具类提供：Subject：主体，执行登录的主体。 Subject.login
        Serializable id = subject.getSession().getId();   //获取subject这个主体对应的携带的sessionId
        System.out.println("info请求的SessionId：" + id);
        //查询用户信息
        //来源于数据库
        //token是用来获得用户信息，来源Shiro
        //先假定一个用户id来做其他信息的查询
        Admin principal = (Admin) subject.getPrincipals().getPrimaryPrincipal();   //从subject主体中获取用户信息
        /**
         * 根据分析：从principal中获取用户基本信息：id
         * 1.根据id判断：if(id==1) 在permisssion中查询role_id=1，对应的permission   admin
         * 2.根据id判断：if(id==5) 在permisssion中查询role_id=2，对应的permission   mall
         * 3.根据id判断：if(id==4) 在permisssion中查询role_id=3，对应的permission   promotion
         * 4.根据上述不同的情况，查询不同的数据进行响应
         */
        InfoBean infoBean = new InfoBean();
        if(principal.getId()==1){

            infoBean.setAvatar("https://s3.ifanr.com/wp-content/uploads/2018/04/avengers-infinity-war-d23-artwork-8k-dl-2048x1152.jpg!720");
            infoBean.setName("admin123");

            ArrayList<String> roles = new ArrayList<>();
            roles.add("超级管理员");
            infoBean.setRoles(roles);

            ArrayList<String> perms = new ArrayList<>();
            perms.add("*");
            infoBean.setPerms(perms);
        }else if(principal.getId()==5){

            infoBean.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");

            infoBean.setName("mall123");

            ArrayList<String> roles = new ArrayList<>();
            roles.add("商场管理员");
            infoBean.setRoles(roles);
            //在permisssion中查询role_id=2
            List<String> malls =authServicelmpl.infoMall(2);

            infoBean.setPerms(malls);
        }
        else if(principal.getId()==4){

            infoBean.setAvatar("https://s3.ifanr.com/wp-content/uploads/2018/04/avengers-infinity-war-d23-artwork-8k-dl-2048x1152.jpg!720");

            infoBean.setName("promotion123");

            ArrayList<String> roles = new ArrayList<>();
            roles.add("推广管理员");
            infoBean.setRoles(roles);
            //在permisssion中查询role_id=3
             List<String> promos = authServicelmpl.infoPromo(3);

            infoBean.setPerms(promos);
        }

        return BaseRespVo.ok(infoBean);
    }

    //http://182.92.235.201:8083/admin/dashboard
    @RequestMapping("admin/dashboard")
    public BaseRespVo dashboard(){
        DataDTO dataDTO = new DataDTO();
        dataDTO.setGoodsTotal(226);
        dataDTO.setOrderTotal(18);
        dataDTO.setProductTotal(666);
        dataDTO.setUserTotal(1);
        return BaseRespVo.ok(dataDTO);
    }


    /**
     * 登出
     * @return
     */
    //http://182.92.235.201:8083/admin/auth/logout
    @OperateLog(opType = "安全操作",opAction = "登出")
    @RequestMapping("admin/auth/logout")
    public BaseRespVo logout(){
//        SecurityUtils.getSubject().logout();
        Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
            subject.logout();
        }
        return BaseRespVo.ok();
    }

    /**
     * 密码修改：需要进一步改进
     * @param updatePasswordBO
     * @return
     */
    //http://localhost:8083/admin/profile/password    POST
    @PostMapping("admin/profile/password")
    public BaseRespVo updatePassword(@RequestBody UpdatePasswordBO updatePasswordBO){
        String newPassword = updatePasswordBO.getNewPassword();
        String oldPassword = updatePasswordBO.getOldPassword();
        String newPassword2 = updatePasswordBO.getNewPassword2();
        if(!newPassword.equals(newPassword2)){
            return BaseRespVo.fail();
        }
        return BaseRespVo.ok();
    }
}